﻿using System.Windows;
using System.ComponentModel.Composition;
using System.ComponentModel.Composition.Hosting;
using System.Reflection;
using System.IO;
using DataModel;
using Helpers;
using System.Data.Entity;

namespace xLibris
{
    /// <summary>
    /// Interaktionslogik für "App.xaml"
    /// </summary>
    public partial class App : Application
    {
        private CompositionContainer _container;

        [Import(typeof(MainWindowViewModel))]
        public MainWindowViewModel _main;

        protected override void OnStartup(StartupEventArgs e)
        {
            base.OnStartup(e);

            if (Compose())
            {
                _main.View().Show();
            }
            else
            {
                Shutdown();
            }
        }
        protected override void OnExit(ExitEventArgs e)
        {
            base.OnExit(e);

            if (_container != null)
            {
                _container.Dispose();
            }
        }

        private bool Compose()
        {
            string currentPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
            var pluginPath = currentPath;
            Logger.LogPath = Path.Combine(currentPath, "Logs");
            var catalog = new AggregateCatalog();
            catalog.Catalogs.Add(new AssemblyCatalog(Assembly.GetExecutingAssembly()));
            catalog.Catalogs.Add(new DirectoryCatalog(pluginPath, "*.dll"));
            CompositionBatch batch = new CompositionBatch();
            batch.AddPart(this);
            _container = new CompositionContainer(catalog);

            try
            {
                _container.Compose(batch);
            }
            catch (CompositionException compositionException)
            {
                MessageBox.Show(compositionException.ToString());
                return false;
            }
            
            foreach (var p in _container.Catalog.Parts)
            {
                Logger.Write("Part: " + p.GetType().Name);
                foreach (var d in p.ExportDefinitions)
                {                    
                    Logger.Write("    " +d.ContractName);
                    foreach (var k in d.Metadata.Keys)
                    {
                        Logger.Write("    - " + k + ": " + d.Metadata[k]);
                    }
                }
            }
            return true;
        }

    }
}
